package com.medical.system.controller;

import com.medical.system.common.Result;
import com.medical.system.model.SysUser;
import com.medical.system.service.SysUserService;
import com.medical.system.util.JwtHelper;
import com.medical.system.util.MD5Helper;
import com.medical.system.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录控制器")
@RestController
@RequestMapping("/admin/system/index")
public class LoginController {

    @Autowired
    private
    SysUserService sysUserService;

    @ApiOperation("登录请求")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        SysUser sysUser = this.sysUserService.getUserInfoUserName(loginVo.getUsername());
        //3.比较密码  （使用用户输入的密码和数据库密码比较）
        String password = loginVo.getPassword();
        String passwordwithMD5 = MD5Helper.encrypt(password);
        System.out.println("密码加密：" + passwordwithMD5);
        if (sysUser == null) {
            return Result.build(null, 214, "账号不正确！！！");
        } else if (sysUser.getStatus().intValue() == 0) {
            return Result.build(null, 217, "账号已停用！！！");
        } else if (!sysUser.getPassword().equals(passwordwithMD5)) {
            return Result.build(null, 215, "密码不正确！！！");
        }
        String token = JwtHelper.createToken(sysUser.getId() + "", sysUser.getUsername());
        HashMap<String, Object> tokenHashMap = new HashMap<>();
        tokenHashMap.put("token", token);
        System.out.println("token:" + token);
        return Result.ok(tokenHashMap);
    }

    @ApiOperation("获取登录角色信息")
    @GetMapping(value = "/info")
    public Result info(HttpServletRequest request) {
        //a.获取请求头的 token 字符串
        String token = request.getHeader("token");
        //b.从token 字符串获取用户名称 (id)  这一步其实就是在校验jwt的token是否合法！！！
        String username = JwtHelper.getUsername(token);
        // c.根据用户名称获取用户信息 （a.基本信息  b.菜单权限信息  和 c.按钮权限信息）
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }
}
